<template>
<div class="search">
  <div class="search__box">
    <input
      type="text"
      name=""
      placeholder="请输入城市或拼音"
      v-model="inputContent"
      @focus="handleOnFocus"
      @blur="handleOnBlur"
    >
  </div>
  <div class="search__content" v-show="isShow" ref="searchBox">
    <div>
      <div
        class="border-bottom"
        v-for="(item, index) of result"
        :key="index"
        @click="handleChangeClick"
      >{{item}}
      </div>
      <div class="border-bottom noresult" v-show="noResult">找不到匹配内容!</div>
    </div>
  </div>
</div>
</template>

<script>
import { mapMutations } from 'vuex'
import BScroll from 'better-scroll'
export default {
  name: 'CitySearch',
  props: {
    citylist: Object
  },
  data () {
    return {
      inputContent: '',
      result: [],
      timer: ''
    }
  },
  methods: {
    handleChangeClick (e) {
      this.changeCity(e.target.innerText)
      this.$router.push('/')
      this.inputContent = ''
    },
    ...mapMutations(['changeCity']),
    handleOnFocus () {
      this.$emit('closeAl')
    },
    handleOnBlur () {
      this.$emit('openAl')
    }
  },
  mounted () {
    this.scroll = new BScroll(this.$refs.searchBox, {click: true})
  },
  computed: {
    isShow () {
      return this.inputContent.length
    },
    noResult () {
      return !(this.result.length)
    }
  },
  watch: {
    inputContent () {
      if (this.timer) {
        clearTimeout(this.timer)
      }
      this.timer = setTimeout(() => {
        const list = []
        for (let i in this.citylist) {
          this.citylist[i].forEach((val) => {
            if (val.spell.indexOf(this.inputContent) > -1 ||
              val.name.indexOf(this.inputContent) > -1) {
              list.push(val.name)
            }
          })
        }
        this.result = list
      }, 20)
    }
  }
}
</script>

<style lang="stylus" scoped>
@import "~@style/variables.styl"
.search
  &__box
    background $bgcolor
    height $header
    text-align center
    input
      width 96%
      height .6rem
      margin-top .14rem
      border-radius 4px
      text-align center
      font-size 12px
  &__content
    position absolute
    top $header*2
    left 0px
    right 0px
    bottom 0px
    overflow hidden
    background-color #eee
    z-index 2
    div
      line-height 26px
      padding-left 10px
      background-color #fff
</style>
